﻿using CKS2320.Common;
using CKS2320.Common.Model;
using CKS2320.Domain.DBEntity;
using CKS2320.Repository.Interface;
using MathNet.Numerics.LinearAlgebra.Factorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using Org.BouncyCastle.Ocsp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static NPOI.HSSF.Util.HSSFColor;

namespace CKS2320.Repository
{
    public class CksLargeTotalRepository : ICksLargeTotalRepository
    {
        private DBContext _dBContext;

        public CksLargeTotalRepository(DBContext dBContext)
        {
            _dBContext = dBContext;
        }

        public int GetAllCount(string Starttime, string Endtime, bool f)
        {
            int total = 0;
            if (f)
            {
                total += _dBContext.Shapes.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime));
                total += _dBContext.Voltagewithstands.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime));
                total += _dBContext.Thicknessdetections.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime));
            }
            else
            {
                total += _dBContext.Shapes.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime) && p.Result == true);
                total += _dBContext.Voltagewithstands.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime) && p.Result == true);
                total += _dBContext.Thicknessdetections.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime) && p.Result == true);
            }
            return total;
        }

        public List<DefectiveDto> GetdefectiveList(string Starttime, string Endtime)
        {
            string sql = string.Format(@"Select COUNT(1) as Num,[PartCode] from [shape] where Result=0 and CreatedTime>=CONVERT(nvarchar(100),'{0}',20) and CreatedTime<=CONVERT(nvarchar(100),'{1}',20)  group by [PartCode] union all   Select COUNT(1) as Num,[PartCode] from [voltagewithstand] where Result = 0 and CreatedTime>=CONVERT(nvarchar(100),'{0}',20) and CreatedTime<=CONVERT(nvarchar(100),'{1}',20)  group by [PartCode] union all  Select COUNT(1) as Num,[PartCode] from [thicknessdetection]  where  CreatedTime>=CONVERT(nvarchar(100),'{0}',20) and CreatedTime<=CONVERT(nvarchar(100),'{1}',20) and  Result=0  group by [PartCode]", Starttime, Endtime);
            return _dBContext.Database.SqlQuery<DefectiveDto>(sql).ToList();
        }

        public List<AllStationCodeDto> GetTotalCount1(string Starttime, string Endtime, int r)
        {
            List<AllStationCodeDto> listAll = new();
            if (r == 1)
            {
                listAll.AddRange(_dBContext.Shapes
                    .Where(n => n.CreatedTime >= DateTime.Parse(Starttime) && n.CreatedTime <= DateTime.Parse(Endtime) && n.Result == false)
                    .Select(p => new AllStationCodeDto() { CreatedTime = p.CreatedTime, StationCode = p.StationCode }).ToList());
            }
            if (r == 2)
            {
                listAll.AddRange(_dBContext.Voltagewithstands
                    .Where(n => n.CreatedTime >= DateTime.Parse(Starttime) && n.CreatedTime <= DateTime.Parse(Endtime) && n.Result == false)
                    .Select(p => new AllStationCodeDto() { CreatedTime = p.CreatedTime, StationCode = p.StationCode }).ToList());
            }
            if (r == 3)
            {
                listAll.AddRange(_dBContext.Thicknessdetections
                    .Where(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime) && p.Result == false)
                    .Select(p => new AllStationCodeDto() { CreatedTime = p.CreatedTime, StationCode = p.StationCode }).ToList());
            }
            return listAll;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public DataQueryResponse QueryListCount()
        {
            DataQueryResponse result = new();
            var shapesList = _dBContext.Shapes.AsNoTracking().ToList();
            var voltageList = _dBContext.Voltagewithstands.AsNoTracking().ToList();
            var thicknessdetectionList = _dBContext.Thicknessdetections.AsNoTracking().ToList();

            result.totalOK += shapesList.Where(p => p.Result == true).Count();
            result.totalOK += voltageList.Where(p => p.VoltageWithstandResult == true).Count();
            result.totalOK += voltageList.Where(p => p.CameraDetectionResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult1 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult2 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult3 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult4 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult5 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult6 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult7 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult1 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult2 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult3 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult4 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult5 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult6 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult7 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.Crfront1WaveDistanceResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.Crfront64WaveDistanceResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.CrlargeEndDistanceResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.CrsmallEndDistanceResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FacadeCurvatureResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.SmallEndDirectionInspectionResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.TotalLengthResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p._3dscannerResult == true).Count();

            result.totalNG += shapesList.Where(p => p.Result == false).Count();
            result.totalNG += voltageList.Where(p => p.VoltageWithstandResult == false).Count();
            result.totalNG += voltageList.Where(p => p.CameraDetectionResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult1 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult2 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult3 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult4 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult5 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult6 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult7 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult1 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult2 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult3 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult4 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult5 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult6 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult7 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.Crfront1WaveDistanceResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.Crfront64WaveDistanceResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.CrlargeEndDistanceResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.CrsmallEndDistanceResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FacadeCurvatureResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.SmallEndDirectionInspectionResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.TotalLengthResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p._3dscannerResult == false).Count();
            return result;
        }

        public async Task<DataQueryResponseNew> QueryListCountNew(TotalReq totalReq)
        {
            DataQueryResponseNew model = new();

            List<DataQuery> list = new();
            int OK = 0;
            int NG = 0;
            int camberNG = 0;
            int ThicknessNG = 0;
            int BOWNG = 0;
            int OtherNG = 0;
            List<Shape> shapesList = new List<Shape>();
            List<Voltagewithstand> voltageList = new List<Voltagewithstand>();
            List<Thicknessdetection> thicknessdetectionList = new List<Thicknessdetection>();
            List<Detectiondetail>? Detectiondetail = new List<Detectiondetail>();
            List<Detectiondetail>? DetectiondetailAll = new List<Detectiondetail>();
            if (!string.IsNullOrEmpty(totalReq.StartTime) && !string.IsNullOrEmpty(totalReq.EndTime))
            {
                DateTime start = DateTime.Parse(totalReq.StartTime);
                DateTime end = DateTime.Parse(totalReq.EndTime); ;
                shapesList = _dBContext.Shapes.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
                voltageList = _dBContext.Voltagewithstands.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
                thicknessdetectionList = _dBContext.Thicknessdetections.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
            }
            else if (!string.IsNullOrEmpty(totalReq.StartTime))
            {
                DateTime start = DateTime.Parse(totalReq.StartTime);
                shapesList = _dBContext.Shapes.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
                voltageList = _dBContext.Voltagewithstands.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
                thicknessdetectionList = _dBContext.Thicknessdetections.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
            }
            else
            {
                DateTime start = DateTime.Now.AddDays(-5);
                //默认只取3月的数据
                shapesList = _dBContext.Shapes.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
                voltageList = _dBContext.Voltagewithstands.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
                thicknessdetectionList = _dBContext.Thicknessdetections.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
                DetectiondetailAll = await _dBContext.Detectiondetails.AsNoTracking().Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToListAsync();
            }
            model = await asyncGetCount(shapesList, voltageList, thicknessdetectionList);
            model.Detected = shapesList.Count;
            if (totalReq.size > 0)
            {
                shapesList = shapesList.Skip((totalReq.page.Value - 1) * totalReq.size.Value).Take(totalReq.size.Value).ToList();
            }
            foreach (var item in shapesList)
            {
                DataQuery dataQuery = new DataQuery();
                dataQuery.PartCode = item.PartCode;
                dataQuery.ShapeID = item.Id.ToString();
                dataQuery.RunType = item.RunType;
                Detectiondetail = DetectiondetailAll.AsParallel().Where(p => p.PartCode == item.PartCode).ToList();
                //OP10
                Detectiondetail? bowmodel = Detectiondetail.Where(p => p.ParentId == item.Id && p.DetectedType == "BOW").FirstOrDefault();
                dataQuery.BOW = bowmodel?.DetectedData.ToString();
                //OP20
                Voltagewithstand? voltagewithstand = voltageList.Where(p => p.PartCode == item.PartCode).FirstOrDefault();
                if (voltagewithstand == null)
                {
                    continue;
                }
                dataQuery.VoltagewithstandID = voltagewithstand.Id.ToString();
                Detectiondetail? potmodel = Detectiondetail.Where(p => p.DetectedType == "DCa" && p.ParentId == voltagewithstand.Id).FirstOrDefault();

                dataQuery.POT = potmodel?.DetectedData.ToString();
                //OP30
                Thicknessdetection? thicknessdetection = thicknessdetectionList.Where(p => p.PartCode == item.PartCode).FirstOrDefault();
                if (thicknessdetection == null)
                {
                    continue;
                }
                dataQuery.ThicknessdetectionID = thicknessdetection.Id.ToString();

                Detectiondetail? camber = Detectiondetail.Where(p => p.DetectedType == "Cam" && p.ParentId == thicknessdetection.Id).FirstOrDefault();
                dataQuery.Camber = camber?.DetectedData.ToString();

                //Detectiondetail? TotalLengthModel = Detectiondetail.Where(p => p.DetectedType == "计算总长" && p.ParentId == thicknessdetection.Id).FirstOrDefault();
                Detectiondetail? TotalLengthModel = Detectiondetail.Where(p => p.DetectedType == "TL" && p.ParentId == voltagewithstand.Id).FirstOrDefault();
                dataQuery.TotalLength = TotalLengthModel?.DetectedData.ToString();

                Detectiondetail? Barb1Model = Detectiondetail.Where(p => p.DetectedType == "FtFS" && p.ParentId == thicknessdetection.Id).FirstOrDefault();
                dataQuery.Barb1 = Barb1Model?.DetectedData.ToString();

                Detectiondetail? Barb2Model = Detectiondetail.Where(p => p.DetectedType == "FtLS" && p.ParentId == thicknessdetection.Id).FirstOrDefault();
                dataQuery.Barb2 = Barb2Model?.DetectedData.ToString();

                Detectiondetail? backbar1Model = Detectiondetail.Where(p => p.DetectedType == "BtFS" && p.ParentId == thicknessdetection.Id).FirstOrDefault();
                dataQuery.BackBarb1 = backbar1Model?.DetectedData.ToString();

                Detectiondetail? backbar2 = Detectiondetail.Where(p => p.DetectedType == "BtLS" && p.ParentId == thicknessdetection.Id).FirstOrDefault();
                dataQuery.BackBarb2 = backbar2?.DetectedData.ToString();

                if (thicknessdetection.FrontThicknessResult1 == true)
                {
                    dataQuery.Thickness = "OK";
                }
                else
                {
                    dataQuery.Thickness = "NG";
                }
                if (thicknessdetection.Result == true)
                {
                    dataQuery.Result = "OK";
                }
                else
                {
                    dataQuery.Result = "NG";
                }
                list.Add(dataQuery);
            }
            //model.listA = list.Where(p => p.RunType == "A").ToList();
            //model.listB = list.Where(p => p.RunType == "B").ToList();
            model.listA = list.Where(p => p.RunType.Contains("A")).ToList();
            model.listB = list.Where(p => p.RunType.Contains("B")).ToList();
            return model;
        }

        public async Task<DataQueryResponseNew> asyncGetCount(List<Shape> shapesList, List<Voltagewithstand> voltageList, List<Thicknessdetection> thicknessdetectionList)
        {
            DataQueryResponseNew model = new();
            int OK = 0;
            int NG = 0;
            foreach (Shape shape in shapesList)
            {
                if (shape.Result == false)
                {
                    NG++;
                    continue;
                }
                Voltagewithstand voltagemodel = voltageList.Where(p => p.PartCode == shape.PartCode).FirstOrDefault();
                if (voltagemodel == null)
                {
                    NG++;
                    continue;
                }
                if (voltagemodel.Result == false)
                {
                    NG++;
                    continue;
                }
                Thicknessdetection thicknessdetectionmodel = thicknessdetectionList.Where(p => p.PartCode == shape.PartCode).FirstOrDefault();
                if (thicknessdetectionmodel == null)
                {
                    NG++;
                    continue;
                }
                if (thicknessdetectionmodel.Result == false)
                {
                    NG++;
                    continue;
                }
                OK++;
            }
            model.NG = NG;
            model.OK = OK;
            return model;
        }

        public async Task<List<Equipmentfailurehistory>> ExportAlarm(TotalReq totalReq)
        {
            DateTime dateTime = DateTime.Now;
            try
            {
                if (!string.IsNullOrEmpty(totalReq.StartTime))
                {
                    dateTime = DateTime.Parse(totalReq.StartTime);
                }
            }
            catch (Exception ex)
            {
            }
            // string sql = string.Format("SELECT t.* FROM PerformanceRecord t WHERE t.CreatedTime
            // IN ( SELECT MAX(CreatedTime) FROM PerformanceRecord WHERE CreatedTime >= DATEADD(DAY,
            // -7,'{0}') GROUP BY CONVERT(DATE, CreatedTime))", dateTime);
            string sql = string.Format(" SELECT * FROM equipmentfailurehistory  WHERE CreatedTime >= DATEADD(DAY, -10,'{0}')ORDER BY  CreatedTime DESC ", dateTime);
            return _dBContext.Database.SqlQuery<Equipmentfailurehistory>(sql).ToList();
        }

        public async Task<List<ExportQueryModel>> ExportQueryListNew(TotalReq totalReq)
        {
            List<ExportQueryModel> list = new List<ExportQueryModel>();
            List<Shape> shapesList = new List<Shape>();
            //List<Detectiondetail>? Detectiondetail = new List<Detectiondetail>();
            //List<Detectiondetail>? DetectiondetailAll = new List<Detectiondetail>();
            List<Voltagewithstand> voltagewithstandList = new List<Voltagewithstand>();
            List<Thicknessdetection> thicknessdetectionList = new List<Thicknessdetection>();
            string? voltageParentId = null;//存放临时parentID
            if (!string.IsNullOrEmpty(totalReq.StartTime) && !string.IsNullOrEmpty(totalReq.EndTime))
            {
                DateTime start = DateTime.Parse(totalReq.StartTime);
                DateTime end = DateTime.Parse(totalReq.EndTime);//结束时间加一个小时保证数据完整性
                shapesList = await _dBContext.Shapes.AsNoTracking().Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).ToListAsync();
                //DetectiondetailAll = await _dBContext.Detectiondetails.AsNoTracking().Where(p => p.CreatedTime >= start && p.CreatedTime <= end.AddHours(1)).ToListAsync();
                voltagewithstandList = await _dBContext.Voltagewithstands.AsNoTracking().Where(p => p.CreatedTime >= start && p.CreatedTime <= end.AddHours(1)).OrderByDescending(p => p.CreatedTime).ToListAsync();
                thicknessdetectionList = await _dBContext.Thicknessdetections.AsNoTracking().Where(p => p.CreatedTime >= start && p.CreatedTime <= end.AddHours(1)).OrderByDescending(p => p.CreatedTime).ToListAsync();
            }
            else if (!string.IsNullOrEmpty(totalReq.StartTime))
            {
                DateTime start = DateTime.Parse(totalReq.StartTime);
                shapesList = await _dBContext.Shapes.AsNoTracking().Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToListAsync();//&&p.PartCode== "P1093818-00-M:SAYH23346624X3Q0"
                //DetectiondetailAll = await _dBContext.Detectiondetails.AsNoTracking().Where(p => p.CreatedTime >= start).ToListAsync();
                voltagewithstandList = await _dBContext.Voltagewithstands.AsNoTracking().Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToListAsync();
                thicknessdetectionList = await _dBContext.Thicknessdetections.AsNoTracking().Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToListAsync();
            }
            else
            {
                DateTime start = DateTime.Now.AddDays(-2);
                //默认只取3月的数据
                shapesList = await _dBContext.Shapes.AsNoTracking().Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToListAsync();
                //DetectiondetailAll = await _dBContext.Detectiondetails.AsNoTracking().Where(p => p.CreatedTime >= start).ToListAsync();
                voltagewithstandList = await _dBContext.Voltagewithstands.AsNoTracking().Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToListAsync();
                thicknessdetectionList = await _dBContext.Thicknessdetections.AsNoTracking().Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToListAsync();
            }
            if (shapesList.Count > 0)
            {
                int rows = 0;
                foreach (Shape item in shapesList)
                {
                    rows++;
                    ExportQueryModel model = new ExportQueryModel();
                    //Detectiondetail = DetectiondetailAll.AsParallel().Where(p => p.PartCode == item.PartCode).ToList();
                    //Detectiondetail? bowmodel = Detectiondetail.Where(p => p.ParentId == item.Id && p.PartCode == item.PartCode && p.DetectedType == "Cam").FirstOrDefault();

                    List<Detectiondetail> bowDetectionModel = _dBContext.Detectiondetails.AsNoTracking().Where(p => p.PartCode == item.PartCode && p.ParentId == item.Id).ToListAsync().Result;
                    model.No = rows;
                    model.PartCode = item.PartCode;
                    model.Bow = bowDetectionModel.Find(f => f.DetectedType == "BOW")?.DetectedData.ToString();
                    model.BowResult = item.Result == true ? "OK" : "NG";
                    model.BowPassageway = item.RunType;
                    model.BowTesttime = item.CreatedTime?.ToString("yyyy/MM/dd HH:mm:ss");
                    //if (model.BowResult == "NG")
                    //{
                    //    continue;
                    //}
                    list.Add(model);
                }

                foreach (Voltagewithstand item in voltagewithstandList)
                {
                    foreach (var shapelist in list)
                    {
                        if (shapelist.PartCode == item.PartCode && string.IsNullOrEmpty(shapelist.PotFinalJudge) && Convert.ToDateTime(shapelist.BowTesttime) < DateTime.ParseExact(item.CreatedTime?.ToString("yyyy/MM/dd HH:mm:ss"), "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture))
                        {
                            //if(item.Result==true)
                            if (shapelist.BowResult == "OK")
                            {
                                List<Detectiondetail> potDetectionModel = _dBContext.Detectiondetails.AsNoTracking().Where(p => p.PartCode == item.PartCode && p.ParentId == item.Id).ToListAsync().Result;
                                shapelist.DcCurrent = potDetectionModel.Find(f => f.DetectedType == "DCa")?.DetectedData?.ToString();
                                shapelist.DcVoltage = potDetectionModel.Find(f => f.DetectedType == "DCv")?.DetectedData?.ToString();
                                shapelist.ResultDc = item.VoltageWithstandResult == true ? "OK" : "NG";
                                shapelist.AcCurrent = potDetectionModel.Find(f => f.DetectedType == "ACa")?.DetectedData?.ToString();
                                shapelist.AcVoltage = potDetectionModel.Find(f => f.DetectedType == "ACv")?.DetectedData?.ToString();
                                shapelist.ResultAc = item.VoltageWithstandResultAC == true ? "OK" : "NG";
                                shapelist.PotFinalJudge = item.Result == true ? "OK" : "NG";//item.VoltageWithstandResult == true && item.VoltageWithstandResultAC == true && item.CameraDetectionResult == true ? "OK" : "NG";
                                shapelist.PotPassageway = item.RunType;
                                shapelist.PotTesttime = item.CreatedTime?.ToString("yyyy/MM/dd HH:mm:ss");
                                shapelist.TotalLength = potDetectionModel.Find(f => f.DetectedType == "TL")?.DetectedData?.ToString();
                                shapelist.TotalLengthResult = item.TotalLengthResult == true ? "OK" : "NG";
                                shapelist.BigPosVerticalValue = potDetectionModel.Find(f => f.DetectedType == "BHV")?.DetectedData?.ToString();
                                shapelist.SmallPosVerticalValue = potDetectionModel.Find(f => f.DetectedType == "SHV")?.DetectedData?.ToString();
                                break;
                            }
                        }
                    }
                }

                foreach (Thicknessdetection item in thicknessdetectionList)
                {
                    foreach (var thicklist in list)
                    {
                        var a = false;
                        if (string.IsNullOrEmpty(thicklist.PotTesttime))
                        {
                            a = false;
                        }
                        else
                        {
                            a = Convert.ToDateTime(thicklist.PotTesttime) < item.CreatedTime;
                        }
                        if (thicklist.PartCode == item.PartCode && string.IsNullOrEmpty(thicklist.CamberResult) && a/*DateTime.ParseExact(item.CreatedTime?.ToString("yyyy/MM/dd HH:mm:ss"), "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)*/)
                        {
                            //暂时屏蔽
                            if (thicklist.PotFinalJudge == "OK" || true)
                            {
                                List<Detectiondetail> camberDetectionModel = _dBContext.Detectiondetails.AsNoTracking().Where(p => p.PartCode == item.PartCode && p.ParentId == item.Id).ToListAsync().Result;
                                thicklist.Camber = camberDetectionModel.Find(f => f.DetectedType == "Cam")?.DetectedData?.ToString();
                                thicklist.CamberResult = item.FacadeCurvatureResult == true ? "OK" : "NG";
                                thicklist.FrontScallopPitch1 = camberDetectionModel.Find(f => f.DetectedType == "FS6")?.DetectedData?.ToString();
                                thicklist.FrontScallopDiameter1 = camberDetectionModel.Find(f => f.DetectedType == "FD6")?.DetectedData?.ToString();
                                thicklist.FrontScallopPitch2 = camberDetectionModel.Find(f => f.DetectedType == "FS24")?.DetectedData?.ToString();
                                thicklist.FrontScallopDiameter2 = camberDetectionModel.Find(f => f.DetectedType == "FD24")?.DetectedData?.ToString();
                                thicklist.BackScallopPitch1 = camberDetectionModel.Find(f => f.DetectedType == "BS6")?.DetectedData?.ToString();
                                thicklist.BackScallopDiameter1 = camberDetectionModel.Find(f => f.DetectedType == "BD6")?.DetectedData?.ToString();
                                thicklist.BackScallopPitch2 = camberDetectionModel.Find(f => f.DetectedType == "BS24")?.DetectedData?.ToString();
                                thicklist.BackScallopDiameter2 = camberDetectionModel.Find(f => f.DetectedType == "BD24")?.DetectedData?.ToString();
                                List<float?> frontList = new List<float?>(7);
                                for (int i = 1; i <= 7; i++)
                                {
                                    frontList.Add(camberDetectionModel.Find(f => f.DetectedType == $"FCT{i}")?.DetectedData);
                                }
                                thicklist.FrontMaxThickness = frontList.Max().ToString();
                                thicklist.FrontMinThickness = frontList.Min().ToString();
                                List<float?> backList = new List<float?>(7);
                                for (int i = 1; i <= 7; i++)
                                {
                                    backList.Add(camberDetectionModel.Find(f => f.DetectedType == $"BCT{i}")?.DetectedData);
                                }
                                thicklist.FrontMaxThickness = frontList.Max().ToString();
                                thicklist.FrontMinThickness = frontList.Min().ToString();
                                thicklist.BackMaxThickness = backList.Max().ToString();
                                thicklist.BackMinThickness = backList.Min().ToString();
                                thicklist.BackThickness7 = camberDetectionModel.Find(f => f.DetectedType == "BCT7")?.DetectedData?.ToString();
                                thicklist.FrontBarbLst1 = camberDetectionModel.Find(f => f.DetectedType == "FtFS")?.DetectedData?.ToString();
                                thicklist.FrontBarbLast = camberDetectionModel.Find(f => f.DetectedType == "FtLS")?.DetectedData?.ToString();
                                thicklist.BackBarbLst1 = camberDetectionModel.Find(f => f.DetectedType == "BtFS")?.DetectedData?.ToString();
                                thicklist.BackBarbLast = camberDetectionModel.Find(f => f.DetectedType == "BtLS")?.DetectedData?.ToString();
                                thicklist.CamberPassageway = camberDetectionModel.FirstOrDefault()?.Description?.ToString();//item.RunType;
                                thicklist.CamberTesttime = camberDetectionModel.FirstOrDefault()?.CreatedTime?.ToString();//item.CreatedTime?.ToString("yyyy-MM-dd HH:mm:ss");
                                thicklist.CamberFinalJudge = item.Result == true ? "OK" : "NG";//thicklist.CamberResult;//item.FacadeCurvatureResult == true && item.Crfront1WaveDistanceResult == true && item.Crfront64WaveDistanceResult == true && item.CrlargeEndDistanceResult == true && item.CrsmallEndDistanceResult == true ? "OK" : "NG";
                                thicklist.Crfront1WaveDistanceResult = item.Crfront1WaveDistanceResult == true ? "OK" : "NG";
                                thicklist.Crfront64WaveDistanceResult = item.Crfront64WaveDistanceResult == true ? "OK" : "NG";
                                thicklist.CrlargeEndDistanceResult = item.CrlargeEndDistanceResult == true ? "OK" : "NG";
                                thicklist.CrsmallEndDistanceResult = item.CrsmallEndDistanceResult == true ? "OK" : "NG";
                                List<float?> fsList = new List<float?>();
                                List<float?> bsList = new List<float?>();
                                List<float?> fdList = new List<float?>();
                                List<float?> bdList = new List<float?>();
                                for (int i = 0; i < 48; i++)
                                {
                                    fsList.Add(camberDetectionModel.Find(f => f.DetectedType == $"FS{i + 1}")?.DetectedData);
                                }
                                for (int i = 0; i < 48; i++)
                                {
                                    bsList.Add(camberDetectionModel.Find(f => f.DetectedType == $"BS{i + 1}")?.DetectedData);
                                }
                                for (int i = 0; i < 48; i++)
                                {
                                    fdList.Add(camberDetectionModel.Find(f => f.DetectedType == $"FD{i + 1}")?.DetectedData);
                                }
                                for (int i = 0; i < 48; i++)
                                {
                                    bdList.Add(camberDetectionModel.Find(f => f.DetectedType == $"BD{i + 1}")?.DetectedData);
                                }
                                thicklist.FrontScallopPitchMax = fsList.Max().ToString();
                                thicklist.FrontScallopPitchMin = fsList.Min().ToString();
                                thicklist.BackScallopPitchMax = bsList.Max().ToString();
                                thicklist.BackScallopPitchMin = bsList.Min().ToString();
                                thicklist.FrontScallopDiameterMax = fdList.Max().ToString();
                                thicklist.FrontScallopDiameterMin = fdList.Min().ToString();
                                thicklist.BackScallopDiameterMax = bdList.Max().ToString();
                                thicklist.BackScallopDiameterMin = bdList.Min().ToString();
                                break;
                            }
                        }
                    }
                }
            }
            return list;
        }

        public async Task<List<ExportQueryCount>> ExportQueryListCount(TotalReq totalReq)
        {
            List<ExportQueryCount> list = new List<ExportQueryCount>();
            string start = null;
            if (!string.IsNullOrEmpty(totalReq.StartTime))
            {
                start = DateTime.Parse(totalReq.StartTime).ToString("yyyy-MM-dd");
            }
            else
            {
                start = DateTime.Now.ToString("yyyy-MM-dd");
            }
            start = start + " 00:00:00";
            DateTime dt = DateTime.Parse(start);
            //从8点开始 8-9
            ExportQueryCount exportQueryCount = new ExportQueryCount();
            List<Shape> shapesList = await _dBContext.Shapes.AsNoTracking().Where(p => p.CreatedTime >= dt && p.CreatedTime <= dt.AddDays(1)).OrderByDescending(p => p.CreatedTime).ToListAsync();
            List<Voltagewithstand> vllist = await _dBContext.Voltagewithstands.AsNoTracking().Where(p => p.CreatedTime >= dt && p.CreatedTime <= dt.AddDays(1)).OrderByDescending(p => p.CreatedTime).ToListAsync();
            List<Thicknessdetection> tklist = await _dBContext.Thicknessdetections.AsNoTracking().Where(p => p.CreatedTime >= dt && p.CreatedTime <= dt.AddDays(1)).OrderByDescending(p => p.CreatedTime).ToListAsync();
            int s = 0;
            int e = 1;
            for (int i = 0; i < 24; i++)
            {
                DateTime dateStart = dt.AddHours(s + i);
                DateTime dateEnd = dt.AddHours(e + i);
                exportQueryCount = GetCount(shapesList, vllist, tklist, dateStart, dateEnd);
                exportQueryCount.No = i + 1;
                exportQueryCount.DatatimeName = dateStart.ToString("yyyy-MM-dd HH:mm:ss") + "--" + dateEnd.ToString("HH:mm:ss");
                list.Add(exportQueryCount);
            }
            return list;
        }

        public async Task<List<PerformanceRecord>> ExportRecord(TotalReq totalReq)
        {
            DateTime dateTime = DateTime.Now;
            try
            {
                if (!string.IsNullOrEmpty(totalReq.StartTime))
                {
                    dateTime = DateTime.Parse(totalReq.StartTime);
                }
            }
            catch (Exception ex)
            {
            }
            string sql = string.Format("SELECT t.* FROM PerformanceRecord t WHERE t.CreatedTime IN ( SELECT MAX(CreatedTime)    FROM PerformanceRecord     WHERE CreatedTime >= DATEADD(DAY, -7,'{0}')      GROUP BY CONVERT(DATE, CreatedTime))", dateTime);
            return _dBContext.Database.SqlQuery<PerformanceRecord>(sql).ToList();
        }

        public ExportQueryCount GetCount(List<Shape> shapesList, List<Voltagewithstand> vllist, List<Thicknessdetection> tklist, DateTime dateStart, DateTime dateEnd)
        {
            ExportQueryCount model = new ExportQueryCount();
            List<Shape> list1 = shapesList.Where(p => p.CreatedTime >= dateStart && p.CreatedTime <= dateEnd).OrderByDescending(p => p.CreatedTime).ToList();
            if (list1 != null && list1.Count > 0)
            {
                model.BowCount = list1.Count;
                model.BowOK = list1.Where(p => p.Result == true).ToList().Count;
                model.BowNG = list1.Where(p => p.Result == false).ToList().Count;
            }

            List<Voltagewithstand> list2 = vllist.Where(p => p.CreatedTime >= dateStart && p.CreatedTime <= dateEnd).ToList();
            if (list2 != null && list2.Count > 0)
            {
                model.hipotCount = list2.Count;
                model.hipotOK = list2.Where(p => p.Result == true).ToList().Count;
                model.hipotNG = list2.Where(p => p.Result == false).ToList().Count;
            }

            List<Thicknessdetection> list3 = tklist.Where(p => p.CreatedTime >= dateStart && p.CreatedTime <= dateEnd).ToList();
            if (list3 != null && list3.Count > 0)
            {
                model.CamberCount = list3.Count;
                model.CamberOK = list3.Where(p => p.FacadeCurvatureResult == true).ToList().Count;
                model.CamberNG = list3.Where(p => p.FacadeCurvatureResult == false).ToList().Count;
            }
            return model;
        }

        public Hashtable ExportQuerydetails(TotalReq req)
        {
            List<Shape> splist = new List<Shape>();
            List<Voltagewithstand> vllist = new List<Voltagewithstand>();
            List<Thicknessdetection> tklist = new List<Thicknessdetection>();
            if (!string.IsNullOrEmpty(req.StartTime) && !string.IsNullOrEmpty(req.EndTime))
            {
                DateTime start = DateTime.Parse(req.StartTime);
                DateTime end = DateTime.Parse(req.EndTime);
                splist = _dBContext.Shapes.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).ToList();
                vllist = _dBContext.Voltagewithstands.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).ToList();
                tklist = _dBContext.Thicknessdetections.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).ToList();
            }
            else if (!string.IsNullOrEmpty(req.StartTime))
            {
                DateTime start = DateTime.Parse(req.StartTime);
                splist = _dBContext.Shapes.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToList();
                vllist = _dBContext.Voltagewithstands.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToList();
                tklist = _dBContext.Thicknessdetections.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToList();
            }
            else
            {
                splist = _dBContext.Shapes.OrderByDescending(p => p.CreatedTime).ToList();
                vllist = _dBContext.Voltagewithstands.OrderByDescending(p => p.CreatedTime).ToList();
                tklist = _dBContext.Thicknessdetections.OrderByDescending(p => p.CreatedTime).ToList();
            }

            List<Detectiondetail> Shapedetaillist = new List<Detectiondetail>();
            foreach (Shape shape in splist)
            {
                Shapedetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == shape.Id).OrderByDescending(p => p.CreatedTime).ToList();
                shape.detaillist = Shapedetaillist;
            }

            List<Detectiondetail> vldetaillist = new List<Detectiondetail>();
            foreach (Voltagewithstand vl in vllist)
            {
                vl.Pushed = true;
                vldetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == vl.Id).OrderByDescending(p => p.CreatedTime).ToList();
                vl.detaillist = vldetaillist;
            }

            List<Detectiondetail> tkdetaillist = new List<Detectiondetail>();
            foreach (Thicknessdetection tk in tklist)
            {
                tk.Pushed = true;
                tkdetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == tk.Id).OrderByDescending(p => p.CreatedTime).ToList();
                tk.detaillist = tkdetaillist;
            }
            Hashtable hashtable = new Hashtable();
            hashtable.Add("OP10", splist);
            hashtable.Add("OP20", vllist);
            hashtable.Add("OP30", tklist);

            return hashtable;
        }

        public List<Detectiondetail> GetThicknessList(TotalReq totalReq)
        {
            List<Detectiondetail> detectiondetails = _dBContext.Detectiondetails.Where(p => p.ParentId.ToString() == totalReq.ThicknessdetectionID).ToList();
            List<Detectiondetail> listF = detectiondetails.Where(p => p.DetectedTypeDisplay.Contains("FCT")).ToList();
            List<Detectiondetail> listB = detectiondetails.Where(p => p.DetectedTypeDisplay.Contains("BCT")).ToList();
            listF.AddRange(listB);
            return listF;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public List<Detectiondetail> QueryList(TotalReq req, PLCRunTypeEnum pLCRunTypeEnum)
        {
            string sqlType = req.Type == 0 ? " a.rn=1" : " 1=1";
            string sql = string.Format($@"select  a.[Id],a.[ParentId],a.[PartCode],a.[PLCIP],a.[DetectedData],a.[DetectedType],a.[DetectedTypeDisplay],a.[DetectedIndex],a.[DetectedStatus],a.[DetectedTime],a.[Description],a.[CreatedTime],a.[ModifiedTime] from (SELECT  [Id] ,[ParentId] ,[PartCode] ,[PLCIP],[DetectedData],[DetectedType],[DetectedTypeDisplay],[DetectedIndex],[DetectedStatus],[DetectedTime],[Description],[CreatedTime],[ModifiedTime],ROW_NUMBER() OVER (PARTITION BY DetectedIndex ORDER BY CreatedTime desc ) AS rn FROM  detectiondetail) a
                            left join (select distinct partcode from [dbo].[thicknessdetection]) b on a.partcode = b.partcode
                            where {sqlType}  and a.description='{pLCRunTypeEnum.ToString()}'  order by createdTime desc ");
            if (req.Type == 0 && req.page != null && req.size != null)
            {
                var query = _dBContext.Database.SqlQuery<Detectiondetail>(sql).Skip((req.page.Value - 1) * req.size.Value).Take(req.size.Value).ToList();
                return query;
            }
            var query2 = _dBContext.Database.SqlQuery<Detectiondetail>(sql).ToList();
            return query2;
        }

        /// <summary>
        /// 导出查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public List<ExportQueryListModel> ExportQueryList(PLCRunTypeEnum pLCRunTypeEnum)
        {
            string sql = string.Format($@"select a.PartCode,a.PLCIP,
case when a.PLCIP='192.168.10.100' then 'OP10'
when a.PLCIP='192.168.10.120' then 'OP20'
when a.PLCIP='192.168.10.150' then 'OP30' end StationCode,a.DetectedData,a.DetectedType,a.Description,a.CreatedTime from
                            (SELECT *,ROW_NUMBER() OVER (PARTITION BY DetectedIndex ORDER BY CreatedTime desc ) AS rn FROM  detectiondetail) a
                            left join (select distinct partcode from [dbo].[thicknessdetection]) b on a.partcode = b.partcode
                            where a.description='{pLCRunTypeEnum.ToString()}'  order by createdTime desc ");
            var query = _dBContext.Database.SqlQuery<ExportQueryListModel>(sql).ToList();
            return query;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public OPResult QueryByPartCodeList(string partCode)
        {
            OPResult result = new()
            {
                partCode = partCode
            };
            var shapeList = _dBContext.Shapes.Where(p => p.PartCode == partCode).ToList();
            if (shapeList != null && shapeList.Any())
            {
                foreach (var item in shapeList)
                {
                    result.op10s.Add(new OP10Result() { parentId = item.Id, result = item.Result });
                }
            }
            var voltageList = _dBContext.Voltagewithstands.Where(p => p.PartCode == partCode).ToList();
            if (voltageList != null && voltageList.Any())
            {
                foreach (var item in voltageList)
                {
                    result.op20s.Add(new OP20Result()
                    {
                        parentId = item.Id,
                        result = item.Result,
                        CameraDetectionResult = item.CameraDetectionResult,
                        VoltageWithstandResult = item.VoltageWithstandResult
                    });
                }
            }
            var thicknessList = _dBContext.Thicknessdetections.Where(p => p.PartCode == partCode).ToList();
            if (thicknessList != null && thicknessList.Any())
            {
                foreach (var item in thicknessList)
                {
                    result.op30s.Add(new OP30Result()
                    {
                        parentId = item.Id,
                        result = item.Result,
                        BackThicknessResult1 = item.BackThicknessResult1,
                        BackThicknessResult2 = item.BackThicknessResult2,
                        BackThicknessResult3 = item.BackThicknessResult3,
                        BackThicknessResult4 = item.BackThicknessResult4,
                        BackThicknessResult5 = item.BackThicknessResult5,
                        BackThicknessResult6 = item.BackThicknessResult6,
                        BackThicknessResult7 = item.BackThicknessResult7,
                        Crfront1WaveDistanceResult = item.Crfront1WaveDistanceResult,
                        Crfront64WaveDistanceResult = item.Crfront64WaveDistanceResult,
                        CrlargeEndDistanceResult = item.CrlargeEndDistanceResult,
                        CrsmallEndDistanceResult = item.CrsmallEndDistanceResult,
                        FacadeCurvatureResult = item.FacadeCurvatureResult,
                        FrontThicknessResult1 = item.FrontThicknessResult1,
                        FrontThicknessResult2 = item.FrontThicknessResult2,
                        FrontThicknessResult3 = item.FrontThicknessResult3,
                        FrontThicknessResult4 = item.FrontThicknessResult4,
                        FrontThicknessResult5 = item.FrontThicknessResult5,
                        FrontThicknessResult6 = item.FrontThicknessResult6,
                        FrontThicknessResult7 = item.FrontThicknessResult7,
                        SmallEndDirectionInspectionResult = item.SmallEndDirectionInspectionResult,
                        TotalLengthResult = item.TotalLengthResult,
                        _3dscannerResult1 = item._3dscannerResult
                    });
                }
            }
            return result;
        }

        public List<DataQueryListModel> QueryListDetail(List<Detectiondetail> detailList, IEnumerable<Indicatortolerancezone> indicatorToleranceZonesList, PLCRunTypeEnum PLCRunType)
        {
            List<DataQueryListModel> result = new();

            #region 查询所有检测项

            List<Detectiondetail> All = new();
            var parentList = detailList.Select(p => p.ParentId).Distinct().ToList();
            foreach (var item in parentList)
            {
                All.AddRange(_dBContext.Detectiondetails.Where(p => p.ParentId == item).AsNoTracking().ToList());
            }

            #endregion 查询所有检测项

            List<OPResult> opResult = new();
            var partCodeList = detailList.Select(p => p.PartCode).Distinct().ToList();
            foreach (var item in partCodeList)
            {
                opResult.Add(QueryByPartCodeList(item));
            }
            float? PartLength = All.FirstOrDefault(p => p.DetectedIndex == 10)?.DetectedData;
            foreach (var detail in detailList)
            {
                DataQueryListModel queryModel = new()
                {
                    RunType = PLCRunType.ToString(),
                    DetectedData = detail.DetectedData,
                    PartCode = detail.PartCode ?? "",
                    PartLength = PartLength.ToString() ?? "",
                    DetectedType = detail.DetectedTypeDisplay ?? "",
                    DetectedTime = detail.DetectedTime ?? ""
                };
                bool indicator = true;
                var itemDetail = All.Where(p => p.ParentId == detail.ParentId && p.DetectedIndex == detail.DetectedIndex).ToList();
                foreach (var item in itemDetail)
                {
                    var opInfo = opResult.FirstOrDefault(p => p.partCode == item.PartCode);
                    if (opInfo != null)
                    {
                        bool? op10result = opInfo?.op10s.Where(p => p.parentId == item.ParentId).Select(p => p.result).FirstOrDefault();
                        bool? op20result = opInfo?.op20s.Where(p => p.parentId == item.ParentId).Select(p => p.result).FirstOrDefault();
                        bool? op30result = opInfo?.op30s.Where(p => p.parentId == item.ParentId).Select(p => p.result).FirstOrDefault();
                        if (op10result == true || op20result == true || op30result == true)
                        {
                            indicator = true;
                        }
                        else
                        {
                            indicator = QueryListDetailInfo(item, indicatorToleranceZonesList);
                        }
                    }
                    else
                    {
                        indicator = QueryListDetailInfo(item, indicatorToleranceZonesList);
                    }
                }
                queryModel.Indicator = indicator;
                queryModel.ToleranceZone = indicator;
                queryModel.DetectedResult = indicator;
                result.Add(queryModel);
            }
            return result;
        }

        public bool QueryListDetailInfo(Detectiondetail item, IEnumerable<Indicatortolerancezone> indicatorToleranceZonesList)
        {
            bool indicator = true;
            if (item.DetectedData == 0 || item.DetectedData == 1)
            {
                if (item.DetectedData == 0)
                    indicator = false;
            }
            else
            {
                Indicatortolerancezone indicatortolerancezone = indicatorToleranceZonesList.FirstOrDefault(p => p.Content == item.DetectedType);
                if (indicatortolerancezone != null)
                {
                    if (indicatortolerancezone.ContentType == "0") //正负范围
                    {
                        if ((indicatortolerancezone.Indicator + indicatortolerancezone.ToleranceZone) < item.DetectedData
                            || (indicatortolerancezone.Indicator - indicatortolerancezone.ToleranceZone) > item.DetectedData)
                        {
                            indicator = false;
                        }
                    }
                    else if (indicatortolerancezone.ContentType == "1") //最大值
                    {
                        if (indicatortolerancezone.ToleranceZone < item.DetectedData)
                        {
                            indicator = false;
                        }
                    }
                    else if (indicatortolerancezone.ContentType == "2") //最小值
                    {
                        if (indicatortolerancezone.ToleranceZone > item.DetectedData)
                        {
                            indicator = false;
                        }
                    }
                }
            }
            return indicator;
        }

        /// <summary>
        /// 历史数据趋势
        /// </summary>
        /// <param name="req"></param>
        public IEnumerable<Detectiondetail> HistoryDataTrends(string data, int detectedIndex)
        {
            DateTime startDate = Convert.ToDateTime(data + " 00:00:00");
            DateTime endDate = Convert.ToDateTime(data + " 23:59:59");
            return _dBContext.Detectiondetails.Where(p => p.DetectedIndex == detectedIndex && p.CreatedTime >= startDate && p.CreatedTime <= endDate).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
        }

        /// <summary>
        /// 指标 公差带
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Indicatortolerancezone> GetIndicatorToleranceZones()
        {
            //var result = _dBContext.IndicatorToleranceZones.AsNoTracking().OrderBy(p => p.Content).ToList();
            //List<IndicatorToleranceZoneModel> json = new();
            //foreach (var item in result)
            //{
            //    json.Add(new IndicatorToleranceZoneModel()
            //    {
            //        Plcip = item.Plcip,
            //        Indicator = item.Indicator,
            //        ToleranceZone = item.ToleranceZone,
            //        Content = item.Content,
            //        ContentType = item.ContentType
            //    });
            //}
            //string values = JsonConvert.SerializeObject(json);

            //return _dBContext.IndicatorToleranceZones.AsNoTracking().ToList();
            string text = File.ReadAllText("Indicatortolerancezone.json");
            return JsonConvert.DeserializeObject<List<Indicatortolerancezone>>(text);
        }

        ///// <summary>
        ///// 导出
        ///// </summary>
        ///// <param name="req"></param>
        ///// <returns></returns>
        //public List<ThicknessDetectionModel> ExportQueryList(TotalReq req)
        //{
        //    //var query = _dbCotext.Detectiondetails.OrderByDescending(p=>p.CreatedTime).GroupBy(p=>p.DetectedType)
        //    //                        .Skip((req.page.Value - 1) * req.size.Value).Take(req.size.Value).ToList();

        // var filters = new List<Func<Thicknessdetection, bool>>(); if
        // (!string.IsNullOrEmpty(req.StartTime)) { filters.Add(p => p.CreatedTime >=
        // Convert.ToDateTime(req.StartTime)); } if (!string.IsNullOrEmpty(req.EndTime)) {
        // filters.Add(p => p.CreatedTime <= Convert.ToDateTime(req.EndTime)); } if
        // (!string.IsNullOrEmpty(req.Status)) { filters.Add(p => p.Result == (req.Status.ToLower()
        // == "ok")); } List<Thicknessdetection> thicknessdetections = new(); var query =
        // _dBContext.Thicknessdetections.Where(p => filters.All(filter =>
        // filter(p))).OrderByDescending(p => p.CreatedTime); if (req.page != null && req.size !=
        // null) { thicknessdetections = query.Skip((req.page.Value - 1) *
        // req.size.Value).Take(req.size.Value).ToList(); } else { thicknessdetections =
        // query.ToList(); } if (thicknessdetections != null && thicknessdetections.Any()) { var qs
        // = from a in thicknessdetections join b in _dbCotext.Detectiondetails on a.Id equals
        // b.ParentId select new ThicknessDetectionModel { BackThicknessResult1 =
        // a.BackThicknessResult1, BackThicknessResult2 = a.BackThicknessResult2,
        // BackThicknessResult3 = a.BackThicknessResult3, BackThicknessResult4 =
        // a.BackThicknessResult4, BackThicknessResult5 = a.BackThicknessResult5,
        // BackThicknessResult6 = a.BackThicknessResult6, BackThicknessResult7 =
        // a.BackThicknessResult7, FrontThicknessResult1 = a.FrontThicknessResult1,
        // FrontThicknessResult2 = a.FrontThicknessResult2, FrontThicknessResult3 =
        // a.FrontThicknessResult3, FrontThicknessResult4 = a.FrontThicknessResult4,
        // FrontThicknessResult5 = a.FrontThicknessResult5, FrontThicknessResult6 =
        // a.FrontThicknessResult6, FrontThicknessResult7 = a.FrontThicknessResult7,
        // Crfront1WaveDistanceResult = a.Crfront1WaveDistanceResult, Crfront64WaveDistanceResult =
        // a.Crfront64WaveDistanceResult, CrlargeEndDistanceResult = a.CrlargeEndDistanceResult,
        // CrsmallEndDistanceResult = a.CrsmallEndDistanceResult, EndUpLoad = a.EndUpLoad,
        // FacadeCurvatureResult = a.FacadeCurvatureResult, SmallEndDirectionInspectionResult =
        // a.SmallEndDirectionInspectionResult, StationCode = a.StationCode, TotalLengthResult =
        // a.TotalLengthResult, _3dscannerEnd = a._3dscannerEnd, _3dscannerResult1 =
        // a._3dscannerResult, _3dscannerStart = a._3dscannerStart, Heart1 = a.Heart1, Heart2 =
        // a.Heart2, StartUpLoad = a.StartUpLoad, PartCode = a.PartCode, Result = a.Result, RunType
        // = a.RunType, detaillist = new List<DetectionDetail>() { new DetectionDetail() { Id =
        // b.Id, ParentId = b.ParentId, Description = b.Description, DetectedData = b.DetectedData,
        // DetectedType = b.DetectedType }} };

        //        return qs.ToList();
        //    }
        //    return new List<ThicknessDetectionModel>();
        //}

        public Hashtable GetToDoMesData()
        {
            List<Shape> splist = _dBContext.Shapes.Where(p => p.Pushed == false).ToList();
            List<Detectiondetail> Shapedetaillist = new List<Detectiondetail>();
            foreach (Shape shape in splist)
            {
                shape.Pushed = true;
                Shapedetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == shape.Id).ToList();
                shape.detaillist = Shapedetaillist;
            }
            List<Voltagewithstand> vllist = _dBContext.Voltagewithstands.Where(p => p.Pushed == false).ToList();
            List<Detectiondetail> vldetaillist = new List<Detectiondetail>();
            foreach (Voltagewithstand vl in vllist)
            {
                vl.Pushed = true;
                vldetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == vl.Id).ToList();
                vl.detaillist = vldetaillist;
            }
            List<Thicknessdetection> tklist = _dBContext.Thicknessdetections.Where(p => p.Pushed == false).ToList();
            List<Detectiondetail> tkdetaillist = new List<Detectiondetail>();
            foreach (Thicknessdetection tk in tklist)
            {
                tk.Pushed = true;
                tkdetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == tk.Id).ToList();
                tk.detaillist = tkdetaillist;
            }
            Hashtable hashtable = new Hashtable();
            hashtable.Add("OP10", splist);
            hashtable.Add("OP20", vllist);
            hashtable.Add("OP30", tklist);

            return hashtable;
        }
    }
}